import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import client from './modules/client'
import createPersistedState from 'vuex-persistedstate'
// import createPersistedStatePlugin from './persistedStatePlugin'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {},
  mutations: {},
  modules: {
    user,
    client
  },
  getters: {
    token: (state) => state.user.token,
    userId: (state) => state.user.userId
  },
  // plugins: [createPersistedState({ paths: ['user.token', 'user.userId'] })]
  plugins: [
    createPersistedState({
      // paths: ['user.token', 'user.userId'], // 与 reducer 互斥，作用相同
      storage: {
        getItem: (key) => {
          const val = localStorage.getItem(key)
          console.log('getItem', key, val)
          return val
        },
        setItem: (key, value) => {
          console.log('setItem', key, value)
          localStorage.setItem(key, value)
        },
        removeItem: (key) => {
          console.log('removeItem', key)
          localStorage.removeItem(key)
        }
      },
      getState: (key, storage) => {
        console.log('getState', key)

        setInterval(() => {
          console.log('getState', store.state)
          store.state.user.token = Date.now()
          store.replaceState(store.state)
        }, 2000)
        const res = storage.getItem(key)
        return res ? JSON.parse(res) : undefined
      },
      setState: (key, state, storage) => {
        console.log('setState', key, state)
        storage.setItem(key, JSON.stringify(state))
      },
      subscriber: (store) => {
        console.log('subscriber')
        return (handler) => store.subscribe(handler)
      },
      // 与 paths 互斥，作用相同
      reducer: (state) => {
        console.log('reducer', state)
        // return state
        return {
          user: {
            token: state.user.token,
            userId: state.user.userId
          }
        }
      }
    })
    // createPersistedStatePlugin({
    //   paths: ['user.userId', 'user.token']
    // })
  ]
})

export default store
